package com.leyou.item.listener;

import com.leyou.item.mapper.StockMapper;
import com.leyou.item.pojo.Stock;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

@Component
public class ItemListener {

    @Autowired
    private StockMapper stockMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "leyou.update.stock.queue", durable = "true"),
            exchange = @Exchange(value = "leyou.stock.exchange",
                    ignoreDeclarationExceptions = "true"),
            key = {"order.pay.stock"}))
    public void listenItem(Map<String, List<String>> msg) throws Exception {
        if (CollectionUtils.isEmpty(msg)) {
            // 放弃处理
            return;
        }
        List<String> skuIds = msg.get("orderId");
        if (CollectionUtils.isEmpty(skuIds)) {
            // 放弃处理
            return;
        }
        // 数据库减库
        skuIds.forEach(sku -> {
            String skuId = sku.substring(0, sku.lastIndexOf("="));
            String num = sku.substring(sku.lastIndexOf("=") + 1, sku.length());
            Stock stock = new Stock();
            stock.setSkuId(Long.parseLong(skuId));
            stock.setStock(this.stockMapper.selectByPrimaryKey(skuId).getStock() - Integer.parseInt(num));
            this.stockMapper.updateByPrimaryKey(stock);
        });
    }
}
